<template>
<div class="addGoods">
    <div class="addBaseInfo">
        <p class="addgoods_public_title">基础信息</p>
        <el-card class="box-card">
            <el-form :model="baseInfo" ref="baseInfo" label-width="80px" class="demo-ruleForm" label-position="left">
                <el-form-item label="商品名称" prop="goodsName" :rules="[{ required: true, message: '请输入商品名称'}]">
                    <el-input type="text" v-model="baseInfo.goodsName" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="返利周期" prop="rebate_date">
                    <el-input type="text" @blur="addPostfix('返利周期')" v-model="baseInfo.rebate_date" auto-complete="off"></el-input>
                </el-form-item>
            </el-form>
            <div>
                <ecpUpload :title="photo_tip?'请选择商品图片':'上传或修改商品图片'" :isError="photo_tip" v-model="goodsPhoto" />
            </div>
        </el-card>
    </div>
    <div class="addFormat">
        <p class="addgoods_public_title">规格</p>
        <el-card class="box-card">
            <div class="addFormat_form">
                <div class="addFormat_form_item" v-for="(item,index) in formatArr" :key="index">
                    <div class="addFormat_form_item_group">
                        <input placeholder="规格名称" type="text" v-model="item.attrName" v-validate="{required: true}" data-vv-value-path="attrName" data-vv-name="attrName" :class="{'addFormat_form_item_group_danger':errors.has('attrName')}">
                        <p class="addFormat_form_item_group_tip" v-show="errors.has('attrName')">{{ errors.first('attrName') }}</p>
                    </div>
                    <div class="addFormat_form_item_group">
                        <input placeholder="价格" type="number" v-model.number="item.attrPrice" data-vv-value-path="attrPrice" data-vv-name="attrPrice" :class="{'addFormat_form_item_group_danger':errors.has('attrPrice')}" v-validate="{required: true}">
                        <p class="addFormat_form_item_group_tip" v-show="errors.has('attrPrice')">{{ errors.first('attrPrice') }}</p>
                    </div>
                    <div class="addFormat_form_item_group">
                        <input placeholder="库存" type="number" v-model.number="item.goodsNum" data-vv-value-path="goodsNum" data-vv-name="goodsNum" :class="{'addFormat_form_item_group_danger':errors.has('goodsNum')}" v-validate="{required: true}">
                        <p class="addFormat_form_item_group_tip" v-show="errors.has('goodsNum')">{{ errors.first('goodsNum') }}</p>
                    </div>
                    <div class="addFormat_form_item_group">
                        <input @blur="addPostfix('返利比例',index)" placeholder="返利比例" type="number" v-model.number="item.rebateRatio" data-vv-value-path="rebateRatio" data-vv-name="rebateRatio" :class="{'addFormat_form_item_group_danger':errors.has('rebateRatio')}" v-validate="{required: true}">
                        <p class="addFormat_form_item_group_tip" v-show="errors.has('rebateRatio')">{{ errors.first('rebateRatio') }}</p>
                    </div>
                    <span :class="item.isRatio==1||item.noAccountRebate==1?'partIn_sel':'partIn_no'" class="partIn line50" @click="item.isRatio=item.isRatio==1?0:1">参与返利</span>
                    <span :class="item.noAccountRebate==1?'partIn_sel':'partIn_no'" class="partIn line25" @click="item.noAccountRebate=item.noAccountRebate==1?0:1">可使用未到账返利</span>
                    <img src="~/static/images/button_tool_default.png" alt="" @click="showDialog(index)">
                    <el-dialog :visible.sync="dialogFormVisible">
                        <el-button plain @click="unitePrice()">统一价格</el-button>
                        <el-button plain @click="uniteNum()">统一库存</el-button>
                        <el-button plain @click="uniteRe()">统一返利</el-button>
                        <el-button plain @click="deleteForm()">删除规格</el-button>
                    </el-dialog>
                </div>
                <el-button type="primary" icon="el-icon-plus" circle @click.native="add" size="mini"></el-button>
            </div>
        </el-card>
    </div>
    <div class="addDescribe">
        <p class="addgoods_public_title">商品描述</p>
        <div ref="editor" style="text-align:left;"></div>
        <p :class="{red_tip:discribe_tip,hidden:!discribe_tip}">请添加商品描述</p>
    </div>
    <div class="addServer">
        <p class="addgoods_public_title">服务</p>
        <el-card>
            <el-checkbox-group v-model="checkService" @change="changeServer">
                <el-checkbox v-for="item in serviceList" :key="item.id" :label="item.id" border size="medium">{{item.serviceName}}</el-checkbox>
            </el-checkbox-group>
            <p :class="{red_tip:server_tip,hidden:!server_tip}">请选择服务</p>
        </el-card>
    </div>
    <div class="selSort">
        <p class="addgoods_public_title">选择分类</p>
        <el-card class="selPlatformSort">
            <p>1.选择平台分类</p>
            <el-cascader :show-all-levels="false" expand-trigger="hover" :props="platformProp" :options="platformSort" v-model="selectedPlatformSort" @change="platformSortChange" placeholder="请选择" clearable>
            </el-cascader>
            <p :class="{red_tip:platForm_tip,hidden:!platForm_tip}">请选择平台分类</p>
        </el-card>
        <el-card class="selShopSort">
            <p>2.选择店铺分类</p>
            <el-cascader :show-all-levels="false" expand-trigger="hover" :props="shopProps" :options="shopSort" v-model="selectedShopSort" @change="shopSortChange" placeholder="请选择" clearable>
            </el-cascader>
            <p :class="{red_tip:shop_tip,hidden:!shop_tip}">请选择店铺分类</p>
        </el-card>
    </div>
    <div class="footer">
        <!-- <el-button class="footer__btn" size="mini" round @click.native="save">保存并上架</el-button> -->
        <el-button class="footer__btn" size="mini" round @click.native="saveAndShelf">保存</el-button>
    </div>
</div>
</template>

<script>
if (process.browser) {
  var wangeditor = require("wangeditor");
}
import EcpUpload from "~/components/ecpUpload";
import {
    getShopCategoryList,
    getSupplyServiceList,
    getPurchaseCategoryList
} from "~/api/";
import {
    addGoods, findGoodsForm, updateGoods
} from "~/api/apiv1";
import {
    searchOption
} from "~/utils/";
var editor;
export default {
    components: {
        EcpUpload
    },
    data() {
        return {
            //添加基础信息
            baseInfo: {
                goodsName: "",
                rebate_date: "",
            },
            goodsPhoto: '',
            //添加规格
            formatArr: [{
                attrName: "", //规格名称
                attrPrice: "", //价格
                goodsNum: "", //库存
                rebateRatio: "", //返利比例
                isRatio: 0, //参与返利   1.是0.否
                noAccountRebate: 0 //可使用未到账返利,1.是0.否
            }],
            dialogFormVisible: false,
            currentIndex: 0,
            photo_tip: false,
            discribe_tip: false,
            server_tip: false,
            platForm_tip: false,
            shop_tip: false,
            //添加商品描述
            new_content: "",
            serverarr: [],
            flatFormSortid: [],
            shopSortid: [],
            //添加服务
            checkService: [],
            //选择平台分类
            selectedPlatformSort: [],
            platformProp: {
                value: "id",
                children: "childList",
                label: "name"
            },
            //选择店铺分类
            selectedShopSort: [],
            shopProps: {
                value: "id",
                children: "childList",
                label: "name"
            }
        };
    },
    watch: {
        new_content: {
            handler: function (val, oldVal) {
                this.discribe_tip = val ? false : true
            },
            deep: true
        },
        goodsPhoto: {
            handler: function (val, oldVal) {
                this.photo_tip = val ? false : true
            },
            deep: true
        },
    },
    async asyncData({ app, params }) {
        try {
            const [res1, res2, res3] = await Promise.all([
                getShopCategoryList(app), //获取店铺分类
                getSupplyServiceList(app), //获取服务列表
                getPurchaseCategoryList(app) //获取平台分类
            ]);
            if (res1.code == "0" && res2.code == "0" && res3.code == "0") {
                return {
                    shopSort: searchOption(res1.data.tree),
                    serviceList: res2.data.serviceList,
                    platformSort: searchOption(res3.data.tree),
                    goodId: params.id
                };
            } else {
                return {
                    shopSort: [],
                    serviceList: [],
                    platformSort: [],
                    goodId: params.id,
                    message: res1.message
                };
            }
        } catch (error) {
            console.error(`获取接口错误，错误信息${error}`);
        }
    },
    mounted() {
        editor = new wangeditor(this.$refs.editor);
        // 下面两个配置，使用其中一个即可显示“上传图片”的tab。但是两者不要同时使用！！！
        editor.customConfig.uploadImgShowBase64 = true; // 使用 base64 保存图片
        // editor.customConfig.uploadImgServer = '/upload'  // 上传图片到服务器

        editor.customConfig.zIndex = 100;
        editor.customConfig.height = "500px";              
        editor.customConfig.onchange = html => {
          this.new_content = html;
        };
        editor.create();
    },
    async beforeMount() {
      if (this.goodId=='0') return
      const res = await findGoodsForm(this, this.goodId)
      if (res.code != '0') return this.$alert(res.message, '提示', {type: 'error'})
      const goodInfo = res.data.goodsInfoVo
      this.baseInfo.goodsName = goodInfo.goodsName
      this.baseInfo.rebate_date = goodInfo.rebateCycle
      this.goodsPhoto = goodInfo.goodsImg
      this.formatArr = goodInfo.goodsAttrList
      this.new_content = goodInfo.goodsDesc
      editor.txt.html(this.new_content)
      // this.serverarr = goodInfo.supplyServiceGoodsList
      this.flatFormSortid = goodInfo.purchaseCategoryGoodsList[0].categoryId
      this.selectedPlatformSort[0] = this.flatFormSortid
      this.shopSortid = goodInfo.shopCategoryGoodsList[0].categoryId
      this.selectedShopSort[0] = this.shopSortid
      // this.checkService
      // 商品服务列表
      goodInfo.supplyServiceGoodsList.map(item => {
        if (item.serviceId==null) return
        this.checkService.push(item.serviceId)
        this.serverarr.push({"supplyServiceId":item.serviceId})
      })
    },
    methods: {
        showDialog(index) {
            this.dialogFormVisible = true;
            this.currentIndex = index;
        },
        removeFormat(item) {
            var index = this.formatArr.indexOf(item);
            if (index !== -1) {
                this.addFormat.formatArr.splice(index, 1);
            }
        },
        add() {
            this.formatArr.push({
                attrName: "", //规格名称
                attrPrice: "", //价格
                goodsNum: "", //库存
                rebateRatio: "", //返利比例
                isRatio: 0, //参与返利
                noAccountRebate: 0, //可使用未到账返利
                key: Date.now()
            });
        },
        deleteForm() {
            this.dialogFormVisible = false;
            this.formatArr.splice(this.currentIndex, 1);
        },
        unitePrice() {
            this.dialogFormVisible = false;
            const attrPrice = this.formatArr[this.currentIndex].attrPrice;
            this.formatArr.filter(function (element, index, array) {
                element.attrPrice = attrPrice;
            });
        },
        uniteNum() {
            this.dialogFormVisible = false;
            const goodsNum = this.formatArr[this.currentIndex].goodsNum;
            this.formatArr.filter(function (element, index, array) {
                element.goodsNum = goodsNum;
            });
        },
        uniteRe() {
            this.dialogFormVisible = false;
            const rebateRatio = this.formatArr[this.currentIndex].rebateRatio;
            this.formatArr.filter(function (element, index, array) {
                element.rebateRatio = rebateRatio;
            });
        },
        async saveAndShelf() {
            var curShopSortid = this.selectedShopSort[
                this.selectedShopSort.length - 1
            ];
            this.shopSortid = [{
                categoryId: curShopSortid
            }]; //-----
            var curFlatFormSortid = this.selectedPlatformSort[
                this.selectedPlatformSort.length - 1
            ];
            this.flatFormSortid = [{
                categoryId: curFlatFormSortid
            }]; //-----

            // 商品服务列表
            // this.serverarr = []
            // this.checkService.map(item => this.serverarr.push({"supplyServiceId": item.id}))

            if (this.serverarr[0] && !this.serverarr[0].supplyServiceId) {
                this.serverarr = [];
            }
            if (this.flatFormSortid[0] && !this.flatFormSortid[0].categoryId) {
                this.flatFormSortid = [];
            }
            if (this.shopSortid[0] && !this.shopSortid[0].categoryId) {
                this.shopSortid = [];
            }
            this.$refs["baseInfo"].validate(async valid => {
                //验证基础信息
                this.$validator.validateAll().then(async result => {
                    //验证商品规格
                    this.photo_tip = this.goodsPhoto == '' ? true : false //验证商品图片
                    this.discribe_tip = this.new_content == '' ? true : false //验证商品描述
                    if (!result || !valid) return;
                    if (!this.photo_tip &&!this.discribe_tip) {
                      let res;
                      if (this.goodId == '0') {
                        res = await addGoods(
                            this,
                            this.baseInfo.goodsName,
                            this.baseInfo.rebate_date,
                            this.goodsPhoto,
                            this.formatArr,
                            this.new_content,
                            this.serverarr,
                            this.flatFormSortid,
                            this.shopSortid
                        )
                      } else {
                        res = await updateGoods(
                          this,
                          {
                            id: this.goodId,
                            goodsName: this.baseInfo.goodsName,
                            rebateCycle: this.baseInfo.rebate_date,
                            goodsImg: this.goodsPhoto,
                            goodsAttrList: this.formatArr,
                            goodsDesc: this.new_content,
                            supplyServiceGoodsList: this.serverarr,
                            purchaseCategoryGoodsList: this.flatFormSortid,
                            shopCategoryGoodsList: this.shopSortid
                          }
                        )
                      }
                        // 成功处理
                        if (res.code == "0") {
                            this.$message.success("添加成功");
                            this.$router.replace("/goods/goodsList");
                            return;
                        }
                        // 失败处理
                        this.$msgbox({
                            title: "提示",
                            message: res.message,
                            type: "error"
                        });

                    }
                });
            });
        },
        addPostfix(str, index) {
            // if (str == '返利周期') {
            //     if (this.baseInfo.rebate_date&& this.baseInfo.rebate_date.indexOf("天") == -1) {
            //         this.baseInfo.rebate_date = this.baseInfo.rebate_date + '天'
            //     }
            // } else if (str == '返利比例') {
            //     if (this.formatArr[index].rebateRatio && this.formatArr[index].rebateRatio.indexOf("%") == -1) {
            //         this.formatArr[index].rebateRatio = this.formatArr[index].rebateRatio + '%'
            //     }
            // }
        },
        //选择服务
        changeServer(val) {
          this.serverarr = []
          console.log(this.checkService)
          val.map(id => this.serverarr.push({"supplyServiceId":id}))
        },
        //选择平台分类
        platformSortChange(val) {
            // this.platForm_tip = val ? false : true
        },
        //选择店铺分类

        shopSortChange(val) {
            // this.shop_tip = val ? false : true
        }
    }
};
</script>

<style lang="scss" scoped>
.addGoods {
    padding: 0 100px 0 51px;
    height: 100%;
    background: #f5f6fa;
    .red_tip {
        color: red;
        font-size: 12px;
    }
    & /deep/ {
        .addBaseInfo {
            .el-card {
                border-radius: 10px;
                .el-card__body {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    form {
                        width: 300px;
                        .el-form-item__label {
                            font-size: 13px;
                        }
                        input {
                            height: 35px;
                            border-radius: 20px;
                        }
                    }
                }
            }
        }
        .addFormat {
            &_form {
                &_item {
                    display: flex;
                    align-items: center;
                    margin-bottom: 20px;
                    &_group {
                        width: 150px;
                        height: 45px;
                        input {
                            width: 120px;
                            height: 25px;
                            border-radius: 15px;
                            border: 1px solid #a9a9a9;
                            text-align: center;
                            display: block;
                            margin: 0 auto;
                            &:focus {
                                outline: none;
                            }
                        }
                        &_danger {
                            border-color: red !important;
                        }
                        &_tip {
                            font-size: 12px;
                            color: red;
                            text-align: center;
                        }
                    }
                    .partIn {
                        width: 90px;
                        height: 50px;
                        text-align: center;
                        border-radius: 10px;
                        font-size: 14px;
                        cursor: pointer;
                        margin: 0 10px;
                    }
                    .line50 {
                        line-height: 50px;
                    }
                    .line25 {
                        line-height: 25px;
                    }
                    .partIn_no {
                        background: #eee;
                    }
                    .partIn_sel {
                        color: #fff;
                        background: #409eff;
                    }
                    & /deep/ {
                        .el-dialog {
                            width: 30%;
                            border-radius: 10px;
                            .el-button {
                                display: block;
                                width: 60%;
                                margin: 0 auto;
                                background: transparent;
                                margin-bottom: 10px;
                            }
                        }
                    }
                }
            }
        }
        .addServer {
            .el-checkbox-group {
                display: flex;
                flex-wrap: wrap;
            }
            .el-checkbox {
                margin-bottom: 10px;
                margin-right: 25px;
            }
            .el-checkbox.is-bordered+.el-checkbox.is-bordered {
                margin-left: 0;
            }
        }
        .selPlatformSort {
            margin-bottom: 30px;
            .el-cascader {
                margin-top: 30px;
            }
        }
        .selShopSort {
            .el-cascader {
                margin-top: 30px;
            }
        }
        .footer {
            margin: 100px 0;
            text-align: right;
            &__btn {
                font-size: 12px;
                border-radius: 8px;
                color: #333856;
                border: solid 1px #333856;
            }
        }
    }
}
</style>
